import 'package:flutter/widgets.dart';
import '../app_window.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

class _CustomDoubleTapHelp {
  final GestureTapCallback? onDoubleTap;

  _CustomDoubleTapHelp({this.onDoubleTap});

  final Stopwatch _stopwatch = Stopwatch();
  bool _isWaitingForDoubleTap = false;

  //使用单击自己实现双击
  void callOnTap() {
    if (!_stopwatch.isRunning) {
      _stopwatch.start();
      _isWaitingForDoubleTap = true;

      Future.delayed(const Duration(milliseconds: 300), () {
        if (_isWaitingForDoubleTap) {
          _isWaitingForDoubleTap = false;
          _stopwatch.reset();
        }
      });
    } else {
      if (_stopwatch.elapsedMilliseconds < 300) {
        _isWaitingForDoubleTap = false;
        //回调双击事件
        onDoubleTap?.call();
      }
      _stopwatch.reset();
    }
  }
}

class _MoveWindow extends StatelessWidget {
  final Widget? child;
  final VoidCallback? onDoubleTap;

  //是否自定义实现双击
  final bool useCustomDoubleTap;
  late final _CustomDoubleTapHelp? _customDoubleTapHelp;

  _MoveWindow({
    Key? key,
    this.child,
    this.onDoubleTap,
    this.useCustomDoubleTap = false,
  }) : super(key: key) {
    _customDoubleTapHelp = useCustomDoubleTap ? _CustomDoubleTapHelp(onDoubleTap: _handleParentDoubleTap) : null;
  }

  //回调双击事件
  void _handleParentDoubleTap() {
    if (this.onDoubleTap != null) {
      this.onDoubleTap!();
    } else {
      appWindow.maximizeOrRestore();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onPanStart: (details) {
          appWindow.startDragging();
        },
        onTap: _customDoubleTapHelp?.callOnTap,
        onDoubleTap: useCustomDoubleTap ? null : _handleParentDoubleTap,
        child: this.child ?? Container());
  }
}

class MoveWindow extends StatelessWidget {
  final Widget? child;
  final VoidCallback? onDoubleTap;

  //是否自定义实现双击
  final bool useCustomDoubleTap;

  MoveWindow({
    Key? key,
    this.child,
    this.onDoubleTap,
    this.useCustomDoubleTap = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (child == null) return _MoveWindow(onDoubleTap: this.onDoubleTap, useCustomDoubleTap: useCustomDoubleTap);
    return _MoveWindow(
      onDoubleTap: this.onDoubleTap,
      useCustomDoubleTap: useCustomDoubleTap,
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Expanded(child: this.child!)]),
    );
  }
}

class WindowTitleBarBox extends StatelessWidget {
  final Widget? child;

  WindowTitleBarBox({Key? key, this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (kIsWeb) {
      return Container();
    }
    final titleBarHeight = appWindow.titleBarHeight;
    return SizedBox(height: titleBarHeight, child: this.child ?? Container());
  }
}
